<template>
  <div class="search">
    <Search
      v-model="value"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      class="searchBar"
    >
      <template #action>
        <van-button
          round
          size="small"
          class="search-btn"
          @click="clickSearch"
          color="#FF6157"
          >搜索</van-button
        >
      </template>
    </Search>
    <div class="search-list" :style="`padding-top: ${searchBarHeight}px`">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="finishedText"
        @load="onLoad"
      >
        <Goods v-for="item in goodsList" :key="item.id" :data="item" />
      </van-list>
    </div>
  </div>
</template>

<script>
import { Search } from 'vant'
import Goods from '@/components/goods'
import { searchGoods_get } from '@/api/front/goods'

const pageSize = 10
let page = 1
export default {
  name: 'index',
  components: { Search, Goods },
  data () {
    return {
      value: '',
      world: '',
      loading: false,
      goodsList: [],
      finished: true,
      hasInit: false,
      searchBarHeight: 0
    }
  },
  computed: {
    finishedText () {
      if (!this.hasInit) {
        return ''
      }
      return '没有更多了'
    }
  },
  mounted () {
    const searchBar = document.querySelector('.searchBar')
    this.searchBarHeight = searchBar.offsetHeight
  },
  methods: {
    initData () {
      this.loading = false
      this.hasInit = false
      this.finished = false
      this.goodsList = []
      page = 1
    },
    clickSearch () {
      this.onSearch(this.value)
    },
    onSearch (v) {
      console.log(v)
      console.log('onSearch')
      this.world = v
      this.initData()
      // this.queryList()
    },
    onLoad () {
      console.log('onLoad')
      this.queryList()
    },
    queryList () {
      searchGoods_get({
        data: {
          page,
          pageSize,
          word: this.world
        }
      })
        .then((res) => {
          this.goodsList = [...this.goodsList, ...res.records]
          page++
          if (res.records.length < pageSize) {
            this.finished = true
          }
        })
        .finally(() => {
          this.loading = false
          this.hasInit = true
        })
    }
  }
}
</script>
<style lang="scss" scoped src="./styles/index.scss"></style>
